<template>
  <div>
    <home-header></home-header>
    <home-swiper :List='swiperList'></home-swiper>
    <home-icons :List='iconList'></home-icons>
    <home-recommend :List='recommendList'></home-recommend>
    <home-weekend :List='weekendList'></home-weekend>
  </div>
</template>

<script>
import axios from 'axios'
import HomeHeader from './components/Header.vue'
import HomeSwiper from './components/Swiper.vue'
import HomeIcons from './components/Icons.vue'
import HomeRecommend from './components/Recommend.vue'
import HomeWeekend from './components/Weekend.vue'
// 引入state的目的是当页面切换的时候，我们在app.vue中用keep-alive避免了重复发送ajax请求
//   比如城市一直选北京，来回切换时不需要重新请求ajax
// 但是当切换城市的时候，首页是要跟着切换的，但是我们因为上面的操作并不会重新发送请求了
//   导致比如说我从北京切到上海，还是显示北京的内容
// 所以首先我会在首页的ajax请求地址中作出修改，需要用到state的数据
import { mapState } from 'vuex'

export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  data () {
    return {
      lastCity: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  methods: {
    getHomeInfo () {
      // 然后在这里修改地址
      axios.get('/api/index.json?city=' + this.city).then(this.getHomeInfoSuccess)
    },
    getHomeInfoSuccess (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  computed: {
    ...mapState(['city'])
  },
  mounted () {
    this.getHomeInfo()
    this.lastCity = this.city
  },
  // 再使用一个生命周期函数
  activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }
}
</script>

<style>

</style>
